#include "serialworker.h"
#include <QSerialPort>
#include <QThread>
#include <QDebug>
#include <Utils/bytedatapro.h>
#include <Utils/settingmanager.h>

SerialWorker::SerialWorker(QObject *parent)
    : QObject(parent),m_serial(nullptr),m_running(false) {
    initTimers();
}

SerialWorker::~SerialWorker()
{
    qDebug()<<"~SerialWorker()";
    ColseSerialPort();
}
void SerialWorker::ColseSerialPort() {
    QMutexLocker locker(&m_mutex);
    if (!m_running) return;

    m_running = false;
    if (m_serial) {
        if (m_serial->isOpen()) {
            m_serial->close();
        }
        delete m_serial;
        m_serial = nullptr;
    }
    emit CloseSerialPortSucess();
}


void SerialWorker::EEGStartOrder()
{
    QMutexLocker locker(&m_mutex);
    if (m_running && m_serial && m_serial->isOpen()) {
        m_serial->write(reinterpret_cast<char*>(dualeegStartCollectOrder), sizeof(dualeegStartCollectOrder));
    }
}
void SerialWorker::ECGStartOrder()
{
    QMutexLocker locker(&m_mutex);
    if (m_running && m_serial && m_serial->isOpen()) {
        m_serial->write(reinterpret_cast<char*>(ecgHolterStartCollectOrder), sizeof(ecgHolterStartCollectOrder));
    }
}

void SerialWorker::ECGStopOrder()
{
    QMutexLocker locker(&m_mutex);
    if (m_running && m_serial && m_serial->isOpen()) {
        m_serial->write(reinterpret_cast<char*>(ecgHolterStopCollectOrder), sizeof(ecgHolterStopCollectOrder));
    }
}
void SerialWorker::EEGStopOrder()
{
    QMutexLocker locker(&m_mutex);
    if (m_running && m_serial && m_serial->isOpen()) {
        m_serial->write(reinterpret_cast<char*>(dualeegStopCollectOrder), sizeof(dualeegStopCollectOrder));
    }
    timerRealTimeIndex.stop();

}


void SerialWorker::StartCompute()
{
    MultiUSBDongle_setBioEEGOXDevice_Start();
    MultiUSBDongle_setECG_Holter_Device_StartCompute();
    timerRealTimeIndex.start();

}
void SerialWorker::initTimers()
{
    //timer 用于控制发送指令，两个设备的指令不能连续发送，需要间隔一段时间发送
    timer.setInterval(100);
    connect(&timer,SIGNAL(timeout()),this,SLOT(stopTrans()));

    timerRealTimeIndex.setInterval(1000);
    connect(&timerRealTimeIndex,SIGNAL(timeout()),this,SLOT(updateRealTimeIndex()));
    connect(&timerRealTimeIndex,SIGNAL(timeout()),this,SLOT(updateBrainEneryIndex()));


    timerFFT3DAnaShow.setInterval(5000);
    connect(&timerFFT3DAnaShow,SIGNAL(timeout()),this,SLOT(onFFTAnaShow()));

    timerForStep.setInterval(2000);
    connect(&timerForStep,SIGNAL(timeout()),this,SLOT(onStepShow()));

    timer_DeviceState.setInterval(200);
    connect(&timer_DeviceState,SIGNAL(timeout()),this,SLOT(updateDeviceState()));
}

/** 判断设备是否在线
 * @brief SerialWorker::getDeviceState
 */
void SerialWorker::getDeviceState()
{
    unsigned char isDualEEGExist=MultiUSBDongle_getBioEEGOXDevice_IsExist();
    unsigned char isECGExist=MultiUSBDongle_getECG_HolterDevice_IsExist();
}

void SerialWorker::updateRealTimeIndex()
{
    bool isEEGOff=MultiUSBDongle_getBioEEGOXDevice_EleOFF()==1;
    int eeg_ele=MultiUSBDongle_getBioEEGOXDevice_Electricity();
    int ecg_ele=MultiUSBDongle_getECG_Holter_Device_Electricity();

    bool isECGOff= MultiUSBDongle_getECG_Holter_Device_EleOff()==1;
    float ppgIndex[5]={0};
    MultiUSBDongle_getBioEEGOXDevice_HROXRealTimeIndex(ppgIndex);
    if(!isEEGOff&& ppgIndex[0]>40 &&ppgIndex[0]<220 &&ppgIndex[1]>90 && ppgIndex[1]<100)
    {
        //脉率和血氧满足条件发射到ui线程
        QVector<double> eegRealTimeIndex;
        for(int i=0;i<3;i++)
            eegRealTimeIndex.append(ppgIndex[i]);
        emit newEEGRealIndexData(eegRealTimeIndex);

    }

    // unsigned char realTimeIndex[2]= {0};
    // MultiUSBDongle_getECG_Holter_Device_RealTimeIndex(realTimeIndex);
    // if(realTimeIndex[0]>0)
    // {
    //     //心率
    // }
    // if(realTimeIndex[1]>0){
    //     //呼吸率
    // }




}

void SerialWorker::updateBrainEneryIndex()
{
    double BrainWaveIndex[13];
    double f[100],psd[100];
    MultiUSBDongle_getBioEEGOXDevice_BrainWaveIndex(BrainWaveIndex,f,psd);
    QVector<double>brainEnergyIndex_v;
    QVector<double>f_v,psd_v;
    // for(int i=0;i<80;i++)
    // {
    //     f_v.append(f[i]);
    //     psd_v.append(psd_v[i]);
    // }
    for(int i=0;i<13;i++)
    {
        brainEnergyIndex_v.append(BrainWaveIndex[i]);
    }

    emit newEEGEnergyIndexData(brainEnergyIndex_v,f_v,psd_v);
}



void SerialWorker::OpenSerialPort(const QString &portName, qint32 baudRate)
{
    QMutexLocker locker(&m_mutex);
    if (m_running) return;

    // 创建串口对象
    m_serial = new QSerialPort();
    m_serial->setPortName(portName);
    m_serial->setBaudRate(baudRate);
    m_serial->setDataBits(QSerialPort::Data8);
    m_serial->setParity(QSerialPort::NoParity);
    m_serial->setStopBits(QSerialPort::OneStop);
    m_serial->setFlowControl(QSerialPort::NoFlowControl);

    // 打开串口
    if (!m_serial->open(QIODevice::ReadWrite)) {
        emit errorOccurred(tr("无法打开串口 %1: %2").arg(portName).arg(m_serial->errorString()));
        delete m_serial;
        m_serial = nullptr;
        return;
    }

    m_running = true;
    emit OpenSeriaPortSuccess();

    // 连接数据接收信号
    connect(m_serial, &QSerialPort::readyRead, this, &SerialWorker::readyRead);
}

void SerialWorker::readyRead()
{
    qDebug()<<"3-cthread="<<QThread::currentThreadId();
    QByteArray readComData = m_serial->readAll();
    if(StartCollectFlag && isSaveRawData)
    {
        // stream<<ByteDataPro::instance().CharArrayToHexString(readComData,readComData.size());
    }
    qDebug()<<readComData.size();
    double ecgWave[200]={0}; double respWave[200]={0};int ecg_respLen[1]={0};
    double leftEEGWave[200]={0}; double rightEEGWave[200]={0}; double irWave[200]={0}; double appgWave[200]={0};int eeg_ppgLen[1]={0};
    MultiUSBDongle_TransData(reinterpret_cast<unsigned char*>(readComData.data()), readComData.size(), ecgWave, respWave, ecg_respLen, leftEEGWave, rightEEGWave, irWave, appgWave, eeg_ppgLen);

    // qDebug()<<"ecg_respLen="<<ecg_respLen[0];
    QVector<double>ecgWaveData,respWaveData;
    for(int i=0;i<ecg_respLen[0];i++)
    {
        ecgWaveData.append(ecgWave[i]);
        respWaveData.append(respWave[i]);
    }
    emit newECGWaveData(ecgWaveData,respWaveData);
    QVector<double> leftEEGdata,rightEEGdata,irPPGdata,redPPGdata;
    for(int i=0;i<eeg_ppgLen[0];i++)
    {
        leftEEGdata.append(leftEEGWave[i]);
        rightEEGdata.append(rightEEGWave[i]);
        irPPGdata.append(irWave[i]);
        redPPGdata.append(appgWave[i]);
    }
    emit newEEGWaveData(leftEEGdata,rightEEGdata,irPPGdata,redPPGdata);
}


void SerialWorker::MultiUSBDongleAPI_Init()
{
    MultiUSBDongle_init();
    MultiUSBDongle_getBioEEGOXDevice_StartCollectionOrder(dualeegStartCollectOrder);
    MultiUSBDongle_getBioEEGOXDevice_StopCollectionOrder(dualeegStopCollectOrder);
    MultiUSBDongle_getECG_Holter_Device_StartCollectionOrder(ecgHolterStartCollectOrder);
    MultiUSBDongle_getECG_Holter_Device_InfoOrder(ecgHolterInfoOrder);
    MultiUSBDongle_getECG_Holter_Device_StopCollectionOrder(ecgHolterStopCollectOrder);
    SettingManager BindD("bindDevice");
    QByteArray ecgMac=ByteDataPro::instance().Hexstring2QByteArray(BindD.getValue<QString>("ecgMac", ""));
    QByteArray dualeegMac=ByteDataPro::instance().Hexstring2QByteArray(BindD.getValue<QString>("eegMac", ""));

    MultiUSBDongle_setECG_HolterMac(reinterpret_cast<unsigned char*>(ecgMac.data()));
    MultiUSBDongle_setDualEEGMac(reinterpret_cast<unsigned char*>(dualeegMac.data()));
    qDebug()<<"MultiUSBDongleAPI_Init::"<<"dualeegMac="<<BindD.getValue<QString>("eegMac", "");

}



